<template>
  <div style="height: 100%;border-radius: 10px;">
    <div style="height: 10%;padding: 15px;display: flex;justify-content: space-between">
      <div>
        <el-input v-model="data.inpVal1" style="width: 200px;" placeholder="请输入用户账号"></el-input>
        <el-input v-model="data.inpVal2" style="width: 200px;margin-left: 10px" placeholder="请输入用户名"></el-input>
        <el-button type="primary" @click="load" style="margin-left: 10px">搜索</el-button>
        <el-button plain type="warning" @click="reset" style="margin-left: 10px">重置</el-button>
      </div>
      <div style="display: flex">
        <el-button type="success" @click="addInfo">新增</el-button>
      </div>
    </div>
    <div>
      <el-table
          v-loading="data.loading"
          height="440"
          :data="data.tableData"
          :default-sort="{ prop: 'id', order: 'descending' }"
          @selection-change="handleSelection"
          style="width: 100%;"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="编号" width="55" sortable align="center" />
        <el-table-column prop="username" show-overflow-tooltip label="账号" align="center" />
        <el-table-column prop="name" show-overflow-tooltip label="用户名" align="center" />
        <el-table-column prop="phone" show-overflow-tooltip label="手机号" align="center"></el-table-column>
        <el-table-column prop="role" label="角色" align="center">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" :icon="Edit" size="small" @click="updateInfo(scope.row)" />
            <el-button type="success" :icon="Edit" size="small" @click="allotRole(scope.row)">分配角色</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="del(scope.row.id)"  />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--弹窗-->
    <el-dialog
        title="数据更新"
        v-model="data.dialog"
        width="35%"
        style="padding: 30px"
        :close-on-click-modal="false">
      <el-form ref="userFormRef" :rules="data.rules" :model="data.userForm" label-width="80px">
        <el-form-item prop="username" label="账号：">
          <el-input v-model="data.userForm.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="name" label="用户名：">
          <el-input v-model="data.userForm.name" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码：">
          <el-input v-model="data.userForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号：">
          <el-input v-model="data.userForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <div style="display: flex;justify-content: end">
          <el-button type="success" @click="addAndUpdate">提交</el-button>
          <el-button plain type="primary" @click="data.dialog = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
        title="角色分配"
        v-model="data.roleDialog"
        width="35%"
        style="padding: 30px;height: 500px;"
        :close-on-click-modal="false">
      <el-form ref="userFormRef" :rules="data.rules" :model="data.userForm" label-width="80px">
        <el-form-item prop="role" label="账号：">
          <el-select
              v-model="data.userForm.role"
              placeholder="请选择角色"
          >
            <el-option
                v-for="(item,index) in data.roleOptions"
                :key="index"
                :label="item.roleName + '---' + (item.remark.length > 15 ? '...':item.remark)"
                :value="item.roleName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="display: flex;justify-content: end;position: relative;bottom: -338px;">
        <el-button type="success" @click="addAndUpdate">提交</el-button>
        <el-button plain type="primary" @click="data.roleDialog = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 分页器 -->
    <div style="width: 200px;margin: 10px -100px;position: relative;left: 50%;">
      <!--
          1.@size-change  赋值每页数据数量
          2.@current-change  赋值页码
          3.pageNum 当前页码
          4.pageSize 每页数量
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="data.pageNum"
          :page-sizes="[8, 10, 1000]"
          :page-size="data.pageSize"
          background
          layout="prev, pager, next, sizes, total"
          :total="data.total">
      </el-pagination>
    </div>
  </div>
</template>

<script lang="js" setup>
import {ref, reactive, getCurrentInstance} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";

const {proxy} = getCurrentInstance();
const data = reactive({
  user: JSON.parse(sessionStorage.getItem('user-data')),
  loading: true,
  inpVal1: '',
  inpVal2: '',
  pageNum: 1, // 当前页码
  pageSize: 8, // 每页数量
  total: 0,
  tableData: [],
  ids: [],
  isNull: true,
  dialog: false, // 弹窗
  userForm: {}, // 弹窗表单
  roleDialog: false, // 角色分配弹窗
  roleOptions: [], // 角色数据
  rules: {
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
  }
});

/**
 * 分配角色
 */
const allotRole = (row) => {
  data.userForm = JSON.parse(JSON.stringify(row));
  data.roleDialog = true;
  loadRole();
}
/**
 * 获取角色数据
 */
const loadRole = () => {
  proxy.$request.get('/role/findAll').then(res => {
    if (res.code === '200') {
      data.roleOptions = res.data;
    } else {
      ElMessage({type:'error',message:res.msg});
    }
  });
}



/**
 * 重置
 */
const reset = () =>{
  data.inpVal1 = '';
  data.inpVal2 = '';
  load();
};

/**
 * 新增修改
 */
const addInfo = () => {
  data.userForm = {};
  data.dialog = true;
};
const updateInfo = (row) => {
  data.userForm = JSON.parse(JSON.stringify(row));
  data.dialog = true;
};
const addAndUpdate = () => {
  proxy.$refs['userFormRef'].validate(valid => {
    if (valid) {
      sendSaveOrUpdate();
    }
  });
};
const sendSaveOrUpdate = () => {
  proxy.$request({
    url: data.userForm.id ? '/user/update' : '/user/add',
    method: data.userForm.id ? 'PUT' : 'POST',
    data: data.userForm
  }).then(res => {
    if (res.code === '200') {
      data.dialog = false;
      data.roleDialog = false;
      ElMessage({message: '数据更新成功！', type: 'success'});
      load();
    } else {
      ElMessage({message:res.msg,type:'error'});
    }
  });
}

/**
 * 获取表格中的被选中数据
 */
const handleSelection=(rows)=> {
  data.ids = rows.map(v => v.id);
  data.isNull = data.ids.length <= 0;
};

/**
 * 删除
 */
const delBatch = () => {
  proxy.$confirm('确定删除该条数据？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    proxy.$request.delete('/user/delBatch',{data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage({message: '批量删除成功！', type: 'success'});
        load();
      } else {
        ElMessage({message:res.msg,type:'error'});
      }
    })
  }).catch(() => {});
};
const del = (id) => {
  proxy.$confirm('确定删除该条数据？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    proxy.$request.delete('/user/del/' + id).then(res => {
      if (res.code === '200') {
        ElMessage({message: '删除成功！', type: 'success'});
        load();
      } else {
        ElMessage({message: res.msg, type: 'error'});
      }
    });
  }).catch(() => {});
};

/**
 * 页面加载
 */
const load = ()=>{
  proxy.$request.get('/user/findByPage',{
    params:{
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      username: data.inpVal1,
      name: data.inpVal2,
    }
  }).then(res => {
    if (res.data != null) {
      data.tableData = res.data.tlist
      data.total = res.data.total;
    } else {
      ElMessage({message:res.msg,type:'error'});
    }
    data.loading = false;
  });
}
// 调用函数
load();
/**
 * 赋值分页器
 */
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize;
  load();
};
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum;
  load();
};
</script>
<style scoped>

</style>